package com.woniu.bank.controller;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.bank.dto.UserDTO;
import com.woniu.bank.entity.SysPermission;
import com.woniu.bank.entity.SysUser;
import com.woniu.bank.service.LoginRecorder;
import com.woniu.bank.service.RatedService;
import com.woniu.bank.service.SysPermissionService;
import com.woniu.bank.service.SysUserService;
import com.woniu.bank.util.JWTUtils;
import com.woniu.bank.util.Result;
import com.woniu.bank.vo.EcharVO;
import com.woniu.bank.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: TODO
 * @Author: WangHeng
 * @Date: 2023/1/3 14:33
 */
@RestController
@RequestMapping("users")
@Api(tags = "用户接口", description = "所有的用户接口")
public class UserController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private LoginRecorder<String, String> loginRecorder;
    @Autowired
    private RatedService ratedService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 登陆方法
     */
    @ApiOperation(value = "用户登录", notes = "用户登陆并返回角色拥有的权限菜单以及token和用户信息", httpMethod = "POST")
    @PostMapping("login")
    public Result login(@Valid @RequestBody UserDTO user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Result.error(bindingResult.getFieldError().getDefaultMessage());
        }
        Map map = new HashMap();
        SysUser sysUser = sysUserService.selectByTelAndPwd(user);
        if (sysUser != null) {
            List<SysPermission> sysPermissions = (List<SysPermission>) redisTemplate.opsForValue().get("sysPermissions");
            if (sysPermissions != null && sysPermissions.size() > 0) {
                map.put("sysPermissions", sysPermissions);
            } else {
                redisTemplate.opsForValue().set("sysPermissions", permissionService.selectPermissionByTel(user.getTel(), 0));
                map.put("sysPermissions", redisTemplate.opsForValue().get("sysPermissions"));
            }
            String token = JWTUtils.createToken(user.getTel(), 36000);
            map.put("token", token);
            map.put("user", sysUser);
            return Result.ok().data("登陆成功", map);
        } else {
            return Result.error("登陆失败，用户名或密码错误！！！");
        }
    }

    /**
     * token检查
     *
     * @param token
     * @return
     */
    @PostMapping("check")
    public Result check(@RequestBody String token) {
        if (loginRecorder.get(token) == null) {
            return Result.error("无效token");
        }
        if (StringUtils.isEmpty(token)) {
            return Result.error("无效token");
        }
        return JWTUtils.verifyToken(token) ? Result.ok("有效token") : Result.error("无效token");
    }

    /**
     * 退出时把token删除
     */
    @ApiOperation(value = "退出登录", notes = "退出时把token删除", httpMethod = "DELETE")
    @DeleteMapping("logout")
    public Result logout(HttpServletRequest request) {
        String token = request.getHeader("token");
        //安全推出的时候从LoginRecored中移除
        loginRecorder.remove(token);
        return Result.ok("退出成功");
    }

    /**
     * 查询全部的管理层带分页
     */
    @ApiOperation(value = "所有的管理层用户", notes = "得到所有的用户信息包含分页", httpMethod = "POST")
    @PostMapping("queryAll")
    private Result findAllUser(@RequestBody UserDTO user) {
        PageHelper.startPage(user.getCurrentPage(), user.getPageSize());
        List<UserVO> userList = sysUserService.selectAllUser(user);
        PageInfo<UserVO> pageInfo = new PageInfo<>(userList);
        return Result.ok().data("userList", userList).data("pageInfo", pageInfo);
    }

    /**
     * 改变用户状态（封禁/正常）
     */
    @ApiOperation(value = "修改管理层用户的状态", notes = "修改管理层用户的状态，只传递修改用户id以及修改状态即可 1正常，2封禁", httpMethod = "PUT")
    @PutMapping("changePer")
    private Result changePer(@RequestBody UserDTO user) {
        if (user.getId() == 0) {
            return Result.error("用户id不能为空");
        }
        if ("1".equals(user.getStatus()) || "2".equals(user.getStatus())) {
            int i = sysUserService.updateByPrimaryKeySelective(new SysUser(user.getId(), null, null, null, null, null, user.getStatus()));

            return i > 0 ? Result.ok("修改成功！") : Result.error("修改失败！");

        } else {
            return Result.error("请传递正确的状态：1/2");
        }
    }

    /**
     * 修改用户信息
     */
    @ApiOperation(value = "修改用户信息", notes = "修改用户信息 务必回传 用户id、修改后的密码、真实姓名、生日、头像信息。（账户不支持修改，状态不支持个人修改）", httpMethod = "PUT")
    @PutMapping("updateUserInfo")
    private Result update(@RequestBody UserDTO user) {
        if (user.getId() == 0) {
            return Result.error("用户id不能为空");
        }
        int i = sysUserService.updateByPrimaryKeySelective(new SysUser(user.getId(), null, user.getPassword(), user.getRealName(), user.getBrithday(), user.getHeadImg(), null));
        return i > 0 ? Result.ok("修改成功！") : Result.error("修改失败！");
    }

    /**
     * 添加用户
     */
    @ApiOperation(value = "添加管理层用户", notes = "添加用户-只要用户的手机号即可，密码默认：123456", httpMethod = "POST")
    @PostMapping("add")
    private Result addUser(@Valid @RequestBody SysUser user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Result.error(bindingResult.getFieldError().getDefaultMessage());
        }
        SysUser sysUser = sysUserService.selectByTel(user);
        if (sysUser == null) {
            int i = sysUserService.insertSelective(user);
            return i == 1 ? Result.ok("添加成功！") : Result.error("添加失败！");
        } else {
            return Result.error("账户已存在");
        }
    }

    /**
     * Echar图数据
     * lgy
     */
    @ApiOperation(value = "返回Echarts图数据", notes = "返回前端客户信用等级及各等级人数数据，供前端exharts图展示", httpMethod = "POST")
    @PostMapping("selEc")
    private Result selEc() {
        List<EcharVO> echarVOS = ratedService.selectEc();
        return echarVOS.size() > 0 ? Result.ok().data("echarVOS", echarVOS) : Result.error("查找失败！");

    }

}
